package com.lingnan.conrtroller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lingnan.dto.*;
import com.lingnan.entity.po.Interview;
import com.lingnan.entity.po.JobApplication;
import com.lingnan.entity.po.JobPosition;
import com.lingnan.entity.po.Resume;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.InterviewFeignClient;
import com.lingnan.service.JobApplicationService;
import com.lingnan.service.ResumeService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/resume")
@RequiredArgsConstructor
@Slf4j
public class ResumeController {

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private JobApplicationService jobApplicationService;

    @Autowired
    private InterviewFeignClient interviewFeignClient;//远程服务


    /**
     * 创建简历投递记录
     */
    @PostMapping("createJobApplication")
    public Result createJobApplication(@RequestBody @Valid JobApplication jobApplication) {
        try {
            log.info("创建面试投递记录：{}", jobApplication);
            jobApplicationService.createJobApplication(jobApplication);
        } catch (Exception e) {
            log.error("创建面试投递记录失败：{}", e.getMessage(), e);
            return Result.fail("创建面试投递记录失败");
        }
        return Result.ok("面试投递记录创建成功");
    }

    /**
     * 根据求职者id获取面试投递记录
     * @param
     * @return
     */
    @GetMapping("getJobAppList/{seekId}")
    public Result<List<JobApplication>> getJobApplicationById(@PathVariable("seekId") Long id) {
        List<JobApplication> jobApplications = jobApplicationService.getJobApplicationById(id);
        return Result.ok(jobApplications);
    }

    /**
     * 移动端撤回投递记录
     * @param applicationId
     * @param seekId
     * @return
     */
    @DeleteMapping("withdraw/{applicationId}")
    public Result<String> withdrawJobApplication(@PathVariable("applicationId") Long applicationId,
                                                 @RequestParam("seekId") Long seekId) {
        try {

            boolean success = jobApplicationService.withdrawJobApplication(applicationId, seekId);
            if (success) {
                return Result.ok("投递记录撤回成功");
            } else {
                return Result.fail("撤回失败，投递记录不存在或无权限操作");
            }
        } catch (Exception e) {
            log.error("撤回投递记录失败，applicationId: {}", applicationId, e);
            return Result.fail("撤回失败：" + e.getMessage());
        }
    }
    /**
     * 查看所有简历
     */
    @GetMapping("getResumeList")
    public Result<List<Resume>> list(){
        return Result.ok(resumeService.list());
    }


    /**
     * 创建简历（含PDF上传URI）
     */
    @PostMapping
    public Result createResume(@Validated @RequestBody Resume resume) {
        // 保存到数据库
        resumeService.save(resume);
        return Result.ok(resume.getId());
    }

    /**
     * 更新简历信息（含PDF URI更新）
     */
    @PutMapping("/{id}")
    public Result updateResume(
            @PathVariable("id") Long id,
            @Validated @RequestBody ResumeUpdateDTO dto  // 使用DTO接收
    ) {
        Resume resume = new Resume();
        resume.setId(id);
        resume.setTitle(dto.getTitle());
        resume.setContent(dto.getContent());
        resume.setFileUrl(dto.getFileUrl());
        resume.setIsDefault(dto.getIsDefault());

        resumeService.updateById(resume);
        return Result.ok();
    }

    /**
     * 删除简历
     */
    @DeleteMapping("/{id}")
    public Result deleteResume(@PathVariable("id") Long id) {
        resumeService.removeById(id);
        return Result.ok();
    }

    /**
     * 根据ID获取简历详情
     */
    @GetMapping("/{id}")
    public Result<Resume> getResumeById(@PathVariable("id") Long id) {
        return Result.ok(resumeService.getById(id));
    }

    /**
     * 根据seekId获取简历详情
     */
    @GetMapping("getResumesBySeekId/{seekId}")
    public Result<List<Resume>> getResumesBySeekId(@PathVariable("seekId") Long seekId) {
        return Result.ok(resumeService.list(new LambdaQueryWrapper<Resume>().eq(Resume::getSeekerId, seekId)));
    }


    /**
     * 设置默认简历
     */
    @PutMapping("/setDefault/{id}")
    public Result setDefaultResume(@PathVariable("id") Long id) {
        Resume resume = resumeService.getById(id);
        if (resume == null) {
            return Result.fail("简历不存在");
        }

        // 清除该用户的所有默认状态
        resumeService.lambdaUpdate()
                .eq(Resume::getSeekerId, resume.getSeekerId())
                .set(Resume::getIsDefault, false)
                .update();

        // 设置当前简历为默认
        resume.setIsDefault(true);
        resumeService.updateById(resume);

        return Result.ok();
    }

    /**
     * 远程调用插入面试记录,安排面试
     * @param
     * @return
     */
    @PostMapping("/createInterview")
    public Result<Interview> createInterview(@RequestBody Interview interview) {
        return interviewFeignClient.createInterview(interview);
    }
    /**
     * 移动端获取投递记录列表，根据状态进行筛选
     */
@GetMapping("/getJobPosition")
public Result<List<JobPositionDto>> getlist(
        @RequestParam("seekId") Integer seekId,
        @RequestParam(value = "status", required = false) Integer status) {

    return Result.ok(resumeService.getlist(seekId,status));
}


    /**
     * PC端分页查询投递记录列表,返回的dto数据模型可以合并安排面试功能里的数据，一起传递给后端插入面试记录
     */
    @PostMapping("/page")
    public Result<IPage<JobApplicationDto>> getResumePage(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
             @RequestBody JobPostRecordQuery queryParam) {
        IPage<JobApplicationDto> result = jobApplicationService.getListByPage(pageNum, pageSize, queryParam);
        return Result.ok(result);
    }

    /**
     * 更改投递状态
     */
    @PutMapping("/status")
    public Result<Void> updateApplicationStatus(
            @RequestParam("applicationId") Long id,
            @RequestParam("status") Long status) {
        jobApplicationService.updateApplicationStatus(id, status);
        return Result.ok();
    }

    /**
     * 批量更改投递状态
     */
    @PutMapping("/status/batch")
    public Result<Void> batchUpdateApplicationStatus(
            @RequestBody BatchUpdateStatusRequest request) {
        jobApplicationService.batchUpdateApplicationStatus(request.getIds(), Long.valueOf(request.getStatus()));
        return Result.ok();
    }

    //pc端还有个发起沟通功能
}